package com.huawei.ebg.crm.dao.impl;

import com.huawei.ebg.crm.dao.PetDao;
import com.huawei.ebg.crm.entity.Dog;
import com.huawei.ebg.crm.entity.Pet;
import com.huawei.ebg.crm.utils.DBUtil;
import com.sun.javafx.scene.control.skin.VirtualFlow;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class PetDaoImpl implements PetDao {

    @Override
    public int addPet(Pet pet) throws Exception {

        Connection conn= DBUtil.getConnection();
        System.out.println(conn);

        // 2 拼写好sql语句 代码自动生成工作 单表的CRUD全部一次性给你写好
        String sql="insert into crm_pet_t values(?,?,?,?)";

        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setInt(1,pet.getId());
        ps.setString(2,pet.getName());
        ps.setString(3,pet.getColor());
        ps.setInt(4,pet.getAge());

        int i = ps.executeUpdate();
        System.out.println(i);
        return  i;
    }

    @Override
    public Pet findPetById(int id) throws Exception {

        Pet pet = new Dog();

        // 1 获取mysql连接
        Connection conn= DBUtil.getConnection();

        System.out.println(conn);
        // 2 拼写好sql语句 代码自动生成工作 单表的CRUD全部一次性给你写好
        String sql="select * from crm_pet_t where id=?";

        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setInt(1,id);

        ResultSet rs = ps.executeQuery();

        if(rs.next()){

            pet.setId(rs.getInt(1));
            pet.setName(rs.getString(2));
            pet.setColor(rs.getString(3));
            pet.setAge(rs.getInt(4));
        }


        return  pet;
    }

    @Override
    public List<Pet> search(String keyWord) throws Exception {

        List<Pet> pets = new ArrayList<Pet>();

        // 1 获取mysql连接
        Connection conn= DBUtil.getConnection();

        System.out.println(conn);
        // 2 拼写好sql语句 代码自动生成工作 单表的CRUD全部一次性给你写好
        String sql="select * from crm_pet_t where NAME like '%"+keyWord+"'";

        PreparedStatement ps = conn.prepareStatement(sql);

        ResultSet rs = ps.executeQuery();

        while (rs.next()){

            Pet pet = new Dog();
            pet.setId(rs.getInt(1));
            pet.setName(rs.getString(2));
            pet.setColor(rs.getString(3));
            pet.setAge(rs.getInt(4));

            pets.add(pet);
        }


        return  pets;
    }
}
